using MallApi.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MallApi.Filters;
public class ModelValidationFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        if (context?.ModelState == null)
        {
            await next();
            return;
        }

        // 模型绑定后触发校验
        if (!context.ModelState.IsValid)
        {
            var errors = context.ModelState
                .Where(e => e.Value?.Errors != null && e.Value.Errors.Count > 0)
                .ToDictionary(
                    kvp => kvp.Key ?? string.Empty,
                    kvp => kvp.Value?.Errors.Select(e => e.ErrorMessage ?? string.Empty).ToList() ?? new List<string>()
                );

            var response = ApiResult<object>.Error("参数校验失败", -2, errors);

            context.Result = new BadRequestObjectResult(response);
            return;
        }

        await next();
    }
}